package 代码随想录.链表;

import common.ListNode;

public class a19删除链表的倒数第N个结点 {
    static class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode solider = new ListNode();
            solider.next = head;
            ListNode slow = solider;
            ListNode fast = solider;
            n++;
            while (fast != null && n-- > 0) {
                fast = fast.next;
            }
            while (fast != null) {
                fast = fast.next;
                slow = slow.next;
            }
            slow.next = slow.next.next;
            return solider.next;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        ListNode read = ListNode.read(new Integer[]{1, 2, 3, 4, 5});
        int n = 2;
        ListNode listNode = solution.removeNthFromEnd(read, n);
        ListNode.print(listNode);
    }
}
